package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strings"
	"errors"
	"reflect"
	"strconv"
	"fmt"
	"kee/plugin"
)

type DockingworkDeviceService struct {
	BackupId	string
	Comment	string
	CreateDate	string
	Dept	string
	DeviceId	string
	DeviceTroubleDetails	string
	DeviceTroubleType	string
	DeviceType	string
	Id	int
	Plugin	string
	Police	string
	PoliceId	string
	ReceiveDeviceDate	string
	Unit	string
}

func InsertSdv(sdv DockingworkDeviceService) (err error) {
	o := orm.NewOrm()
	var id int64
	id, err = o.Insert(&sdv)
	if err == nil {
		beego.Info("Successfully insert the Sdv when Id=" + strconv.FormatInt(id,10))
	}
	return err
}

func GetAllSdvCount() (count int64, err error){
	count, err = Orm.QueryTable("dockingwork_device_service").Count()
	return
}

func GetOneSdv(id int) DockingworkDeviceService {
	o := orm.NewOrm()
	sdv := DockingworkDeviceService{Id: id}

	err := o.Read(&sdv)

	if err == orm.ErrNoRows {
		beego.Error("Can not find")
	} else if err == orm.ErrMissPK {
		beego.Error("Can not find the Primary key")
	} else {
		beego.Info("Successfully Find the Sdv when id=" + strconv.Itoa(sdv.Id))
	}
	return sdv
}

func GetAllSdv(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error){
	o := orm.NewOrm()
	qs := o.QueryTable(new(DockingworkDeviceService))

	for k, v := range query{
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}

	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []DockingworkDeviceService
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				cache_expire, _ := beego.AppConfig.Int("cache_expire")
				plugin.SetCache("GetCost.id."+fmt.Sprintf("%d", v.Id), v, cache_expire)
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

func UpdateSdv(service DockingworkDeviceService) (err error) {
	o := orm.NewOrm()
	var id int64
	id, err = o.Update(&service)
	if err == nil {
		beego.Info("Successfully update the Sdv when id=" + strconv.FormatInt(id, 10))
	}
	return err
}

func DeleteSdv(id int) (err error) {
	o := orm.NewOrm()
	if num, err := o.Delete(&DockingworkDeviceService{Id: id}); err == nil {
		beego.Info("Successfully delete the Sdv where id=" + strconv.FormatInt(num, 10))
	}
	return err
}